import React, {useCallback, useMemo} from 'react'
import { connect } from 'react-redux'
import {bindActionCreators} from 'redux'
import './App.css'

import Header from '../common/Header'
import CitySelector from '../common/CitySelector'
import DateSelector from '../common/DateSelector'
import DepartDate from './DepartDate'
import HighSpeed from './HighSpeed'
import Journey from './Journey'
import Submit from './Submit'
import {h0} from '../common/fp'

import {exchangeFromTo, clickShowCity, clickHideCity, fetchCityData, setSelectedCity, showDateModel, hideDateModel, setDepartDate, toggleHighSpeed} from './actions'

function App(props) {
  const {from, to, dispatch, isCityModalOpen, cityData, isLoadingCityData, departDate, isDateModalOpen, highSpeed} = props
  const onBack = useCallback(() => {
      window.history.back();
  }, []);

  // const doExchangeFromTo = useCallback(() => {
  //   dispatch(exchangeFromTo())
  // }, [])
  // const doClickShowCity = useCallback((m) => {
  //   dispatch(clickShowCity(m))
  // }, [])
  const cbs = useMemo(() => {
    return bindActionCreators({
      exchangeFromTo,
      clickShowCity
    }, dispatch)
  }, [])
  
  const citySelectorCbs = useMemo(() => {
    return bindActionCreators({
      onBack: clickHideCity,
      fetchCityData,
      onSelect: setSelectedCity
    }, dispatch)
  }, [])

  const departDateCbs = useMemo(() => {
    return bindActionCreators({
      onClick: showDateModel
    }, dispatch)
  }, [])

  const dateSelectorCbs = useMemo(() => {
    return bindActionCreators({
      onBack: hideDateModel
    }, dispatch)
  }, [])

  const onSelectDate = useCallback(day => {
    console.log('day =', day)
    if(!day || h0() > day) return
    dispatch(setDepartDate(day))
    dispatch(hideDateModel())
  }, [])

  const highSpeedCbs = useMemo(() => {
    return bindActionCreators({
      toggle: toggleHighSpeed
    }, dispatch)
  }, [])

  return (
    <div>
      <div className="header-wrapper"><Header title="火车票" onBack={onBack} /></div>
      <form action="./query.html" className='form'>
        <Journey 
          from={from} 
          to={to} 
          {...cbs}
          // exchangeFromTo={doExchangeFromTo()} 
          // clickShowCity={doClickShowCity(m)}
          />
        <DepartDate time={departDate} {...departDateCbs} />
        <HighSpeed {...highSpeedCbs} highSpeed={highSpeed} />
        <Submit />
        <CitySelector
          show={isCityModalOpen}
          cityData={cityData}
          isLoading={isLoadingCityData}
          {...citySelectorCbs}
        />
        <DateSelector show={isDateModalOpen} {...dateSelectorCbs} onSelect={onSelectDate} />
      </form>
    </div>
  )
}

export default connect(
  function mapStateToProps(state) {
    return state
  },
  function mapDispatchToProps(dispatch) {
    return {dispatch}
  }
)(App)